package main

import (
	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	"github.com/redis/go-redis/v9"
	"jk-webook/internal/web"
	"jk-webook/internal/web/middleware"
	"jk-webook/pkg/ginx/middleware/ratelimit"
	"strings"
	"time"
)

func InitGin(mdls []gin.HandlerFunc, hdl *web.UserHandler) *gin.Engine {
	server := gin.Default()
	server.Use(mdls...)
	hdl.RegisterUserRoutes(server)
	return server
}

func InitMiddlewares(client redis.Cmdable) []gin.HandlerFunc {
	return []gin.HandlerFunc{
		ratelimit.NewBuilder(client, time.Minute, 100).Build(),
		cors.New(cors.Config{
			AllowHeaders:     []string{"Content-Type", "Authorization"},
			AllowCredentials: true,
			AllowOriginFunc: func(origin string) bool {
				if strings.HasPrefix(origin, "http://localhost") {
					return true
				}
				return strings.Contains(origin, "xxx.com")
			},
			//我给到前端的是什么
			ExposeHeaders: []string{"x-jwt-token"},
			MaxAge:        12 * time.Hour,
		}),
		middleware.NewLoginJwtMiddleWareBuilder().Build(),
	}
}
